const CryptoJS = require('crypto-js')
const qs = require('querystringify');

const secret_id = "";
const secret_key = "";
// 确定签名的当前时间和失效时间
const current = 1627801035971
const expired = current + 86400;  // 签名有效期：1天

const arg_list = {
  secretId: secret_id,
  currentTimeStamp: current,
  expireTime: expired,
  // random: Math.round(Math.random() * Math.pow(2, 32))

  // 这个地方先用固定的参数， 方便和 腾讯的
  // https://video.qcloud.com/signature/ugcgenerate.html 做对比，一模一样说明是OK了
  random: 3
}

const orignal = qs.stringify(arg_list)
console.log('orignal', orignal)

const sha1 = CryptoJS.algo.SHA1.create()
sha1.update(orignal)
const hash = sha1.finalize()

console.log('字符串转buffer', stringToArrayBuffer(orignal))
console.log('hash', hash.toString(CryptoJS.enc.Base64))


function stringToArrayBuffer(str) {
  var bytes = new Array();
  var len, c;
  len = str.length;
  for (var i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if (c >= 0x010000 && c <= 0x10FFFF) {
      bytes.push(((c >> 18) & 0x07) | 0xF0);
      bytes.push(((c >> 12) & 0x3F) | 0x80);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000800 && c <= 0x00FFFF) {
      bytes.push(((c >> 12) & 0x0F) | 0xE0);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000080 && c <= 0x0007FF) {
      bytes.push(((c >> 6) & 0x1F) | 0xC0);
      bytes.push((c & 0x3F) | 0x80);
    } else {
      bytes.push(c & 0xFF);
    }
  }
  var array = new Int8Array(bytes.length);
  for (var i = 0; i <= bytes.length; i++) {
    array[i] = bytes[i];
  }
  return array.buffer;
}




